import os.path
import re
import pandas as pd
import numpy as np
from netmiko import ConnectHandler,SSHDetect, Netmiko
import threading
from io import StringIO

def show_interface_brief(output):
    output_ip_interface=pd.read_csv(StringIO(output),sep='\s+')
    # #解析show ip interface brief
    # output1=output.split('\n')
    # output2=[re.split(r'\s+',x.strip()) for x in output1]
    # output_ip_interface=pd.DataFrame(output2,columns=output2[0]) #output2必须要是单列表
    # output_ip_interface=output_ip_interface[1:]
    # output_ip_interface=output_ip_interface.reset_index(drop=True)
    return output_ip_interface


def show_ip_interface_brief(output):
    output_ip_interface=pd.read_csv(StringIO(output),sep='\s+')
    # #解析show ip interface brief
    # output1=output.split('\n')
    # output2=[re.split(r'\s+',x.strip()) for x in output1]
    # output_ip_interface=pd.DataFrame(output2,columns=output2[0]) #output2必须要是单列表
    # output_ip_interface=output_ip_interface[1:]
    # output_ip_interface=output_ip_interface.reset_index(drop=True)
    return output_ip_interface



def show_ip_ospf_neighbor_detail(output):
    # output1 = output.split('\n')
    data_dir= {}
    pattern1='OSPF Router with ID \((.*)\) \(Process ID 1\)'
    data_dir['OSPF_ID'] = re.findall(pattern1, output)
    pattern2='Neighbor (\d+.\d+.\d+.\d+)'
    data_dir['Neighbor'] = re.findall(pattern2, output)
    pattern3='    In the area (.*)'
    data_dir['area'] = re.findall(pattern3, output)


def show_running_config_opsfv2(output):
    pass




def netmiko_collect_info(host_ip,command,path):

    dev = {
        'device_type': 'zte_zxros',
        'host':   host_ip,
        'username': 'zte',
        'password': 'zte',
        'port' : 22,          # optional, defaults to 22
    }

    net_connect = ConnectHandler(**dev)
    run_time=net_connect.send_command('show clock')
    run_time=pd.to_datetime(run_time)
    print(run_time)
    output = net_connect.send_command(command)
    print(host_ip,command)
    print(output)


    #创建command指令执行后结果存放路径
    base_dir=path+command+'\\'

    #调用指令函数，处理响应的输出结果，处理为pd.DataFrame格式
    #如果没有该函数，则不处理，输出None
    try:
        result=eval(command.replace(' ','_').replace('-','_'))(output)
        if isinstance(result, pd.DataFrame):
            result['run_time']=run_time #增加字段run_time，记录采集时间
            result['host_ip']=host_ip #增加字段host_ip,标识采集设备
            # print(result)
            # result.to_csv(base_dir+host_ip.replace(':','_')+'.csv')#将同一指令的文件存储到相同的文件夹中
            global command_result_all
            lock.acquire()
            print(result)
            command_result_all=pd.concat([command_result_all,result])
            lock.release()
        command_result_all=command_result_all.reset_index(drop=True)
        return command_result_all
    except NameError:
        print(output)
        print(command+'函数未定义')
        return None



# #配合多线程合并多个本地数据
# def concat_file(path,command):
#     #合多台设备同一个command的输出结果
#     base_dir=path+command #获取command输出的目录
#
#     file_name=os.listdir(base_dir) #获取base_dir目录下的所有文件
#     command_result_all=pd.DataFrame()
#     for x in file_name:
#         path_final=os.path.join(base_dir,x)
#         file=pd.read_csv(path_final)
#         command_result_all=pd.concat([command_result_all,file])#合并多个主机的command的输出结果
#     return command_result_all


#多线程下载数据到本地，并合并数据
def multi_thread_send_command_and_collect_info(host_ip_list,command,path):
    #批量给多台设备下发指令
    for i in range(0,len(host_ip_list)):
        t = threading.Thread(target=netmiko_collect_info, args=(host_ip_list[i], command, path))
        t.start()
        t.join()
    # concat_file(path, command)

def multi_process_send_command():
    pass

#下发conf t配置指令
def send_config_command(host_ip,config_commands):
    dev = {
        'device_type': 'zte_zxros',
        'host':   host_ip,
        'username': 'zte',
        'password': 'zte',
        'port' : 22,          # optional, defaults to 22
    }

    net_connect = ConnectHandler(**dev)
    output = net_connect.send_config_set(config_commands)
    print(output)



# 显示所有列
pd.set_option('display.max_columns', None)

#批量采集脚本--all-host
path='C:\\Users\\JS_weihu13\\PycharmProjects\\hzy-pythonProject1\\'

host_ip_list=['129.60.161.169', '129.60.161.170']
commands=['show ip interface brief','show interface brief']
# commands=['show interface brief']
# commands=['show interface xlgei-0/1/1/3']
# commands=['show interface']

# 共享资源
command_result_all=pd.DataFrame()
# 创建一个锁对象
lock = threading.Lock()

commands_result_all={}
for command in commands:
    global command_result_all
    command_result_all = pd.DataFrame()
    multi_thread_send_command_and_collect_info(host_ip_list,command,path)
    command_result_all.to_csv(command+'.csv')
    commands_result_all[command]=command_result_all



###################################################################################
#
# #找出端口down的host及其对于端口，生成no shutdown的指令，并下发
# output_ip_interface=commands_result_all['show ip interface brief']
# down_interface=output_ip_interface[(output_ip_interface['IP-Address']!='unassigned')&(output_ip_interface['Admin']=='down')]
# # # 两个条件筛选
# # result = df[(df['年龄']>20)&(df['成绩']>80)]
# # print(result)
# if not down_interface.empty:
#     for host_ip in down_interface['host_ip'].unique():
#         host_down_port=down_interface[down_interface['host_ip']==host_ip]['Interface']
#         print(host_ip,'interface is down:',host_down_port)
#         host_config_command=[]
#         for x in host_down_port:
#             host_config_command.append('interface '+x)
#             # host_config_command.append('no shutdown')
#             host_config_command.append('show this')
#             host_config_command.append('exit')
#             print(host_config_command)
#
#         send_config_command(host_ip,host_config_command)
# else:
#     print('all interface is up')
#######################################################################################################


# #单步执行
# def show_interface(output):
#     # 端口流量及状态检查，解析show interface xgei-x/x/x/x
#     output1=output.split('\n')
#     columns=['Interface','MTU','rx_bytes','tx_bytes']
#
#     result = re.findall(pattern, output)
#
#
#     output_interface= pd.DataFrame()
#     output_interface['Interface']=pd.Series(re.split('\\s+',output1[0].strip())[0])
#     for line in output1:
#         if 'In_Bytes' in line:
#             output_interface['rx_bytes']=pd.Series(re.split('\\s+',a.strip())[1])
#         if 'E_Bytes' in line:
#             output_interface['tx_bytes']=pd.Series(re.split('\\s+',a.strip())[1])
#
#     return output_interface
#
#
# #采集接口的流量信息
# commands=['show interface']







#获取接口，拼接指令
# interface_info=commands_result_all['show interface brief'][['Interface','host_ip']]
# command_list= {}
# for i in range(0,len(interface_info)):
#     host_ip=interface_info.host_ip[i]
#     interface=interface_info.Interface[i]
#     command_list[host_ip]=[]
#     command_list[host_ip].append('show interface '+interface)
#     # show_interface_xxx(output)
#
# for key, value in command_list.items():
#     print(key, value)
#     host_ip=key
#     command=value
#     interface_liuliang_info=netmiko_collect_info(host_ip, command, path)
#




